<?php
/**
 * 微论坛模块微站定义
 *
 * @author 微网融
 * @url http://bbs.we7.cc/
 */
defined('IN_IA') or exit('Access Denied');

class Wwr_bbsModuleSite extends WeModuleSite {
    private $nopic='../addons/wwr_bbs/app/resource/images/nopic.jpg';

    function __construct(){
        global $_W, $_GPC;
        /*
        if($_GPC['c']=='entry'){
            $userinfo = array();
            load() -> model('mc');

            $userinfo = mc_oauth_userinfo();
            if (empty($userinfo['openid'])) {
                die("<!DOCTYPE html>
                <html>
                    <head>
                        <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'>
                        <title>抱歉，出错了</title><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'><link rel='stylesheet' type='text/css' href='https://res.wx.qq.com/connect/zh_CN/htmledition/style/wap_err1a9853.css'>
                    </head>
                    <body>
                    <div class='page_msg'><div class='inner'><span class='msg_icon_wrp'><i class='icon80_smile'></i></span><div class='msg_content'><h4>请在微信客户端打开链接</h4></div></div></div>
                    </body>
                </html>");
            }

        }
        */
    }

    //论坛首页
    public function doMobileIndex() {

        //        define("MODULE_NAME", "wwr_bbs");
        //        $_W['siteroot'] = 'http://wwr/';
        //        !defined('FX_URL')  &&define('FX_URL', $_W['siteroot'] . 'addons/'. MODULE_NAME . '/');
        global $_W, $_GPC;
        $config = $this->module['config'];
        $categorys = pdo_fetchall("select * from ".tablename('wwr_bbs_category')." where weid = ".$_W['uniacid']);
        $operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
        $pindex = max(1, intval($_GPC['page']));
        //当前页码
        $psize = max(1, intval($_GPC['psize']));
        //设置分页大小
        $pagetitle = "论坛首页";

        if ($operation=='ajax'){
            $condition = " pid = 0 and weid = '{$_W['uniacid']}' ";
            if($_GPC['cid']){
                $condition .= "and cid = '{$_GPC["cid"]}' ";
            }
            $field = "id, title, pic, createtime,openid,hits";
            $activity = pdo_fetchall ("SELECT $field FROM " . tablename ('wwr_bbs') . " WHERE $condition ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
            $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('wwr_bbs') . " WHERE $condition");
            foreach ($activity as &$v){

                $v['avatar'] = $this->getavatar($v['openid']);
                $v['nickname'] = $this->getnickname($v['openid']);
                $v['createtime'] = $this->from_time($v['createtime']);
                if($v['pic']==''){$v['pic']=$this->nopic;}
                //                echo $v['avatar'];
                $v['replay'] = pdo_fetchcolumn("select COUNT(*) from ".tablename('wwr_bbs')." where pid = ".$v['id']);
                $v['zan'] = pdo_fetchcolumn("select COUNT(*) from ".tablename('wwr_bbs_zan')." where bbsid = ".$v['id']);
            }
            //array_merge数组拼接
            $tmp['lists']=$activity;
            $tmp['tpage']=(empty($psize) || $psize < 0) ? 1 : ceil($total / $psize);
            die(json_encode($tmp));
            //include $this->template ('ajax_index');
        }else{
            include $this->template('index');
        }
    }
    //板块列表
    public function doMobileCate(){
        //        $_W['siteroot'] = 'http://192.168.1.13/';
        include $this->template('cate');
    }
    //发布帖子
    public function doMobilePost(){
        global $_W, $_GPC;
        $cid = intval ( $_GPC ['cid'] );
        $config = $this->module['config'];
        $categorys = pdo_fetchall("select * from " .tablename('wwr_bbs_category'). " where weid = " .$_W['uniacid']);
        $pagetitle = "发布帖子";
        //if ($config['guanzhu_join']==2 && empty($_W['fans']['follow']))message('您还未关注,不能发帖.', $this->createMobileUrl('index'), 'warning');
        //$activity = pdo_fetch ("SELECT prize FROM " . tablename ('fx_activity') . " WHERE id = " . $activityid );
        //$activity['prize'] = unserialize($activity['prize']);
        if (checksubmit('submit')) {

            if (empty ( $_GPC ['title'] )) {
                message ('请填写标题');
            }
            if (empty ( $_GPC ['content'] )) {
                message ('请填写内容');
            }

            if(!empty($_GPC['pics'])){
                $pics=implode(',',$_GPC['pics']);
            }else{
                $pics='';
            }

            $data = array (
                'cid' => $_GPC['cid'],
                'weid' => $_W['uniacid'],
                'openid' => $_W['fans']['openid'],
                'title' => $_GPC['title'],
                'pic' => $_GPC['pic'],
                'pics' => $pics,
                'content' => htmlspecialchars_decode($_GPC ['content']),
                'createtime' => time(),
                'status' => $config['reviewstatus']==1 ? 8 : 0
            );

            $result = pdo_insert ('wwr_bbs', $data );
            if ($result){
                $_W['page']['title'] = '发布成功';
                message('发布成功！', $this->createMobileUrl('index'), 'success');
//                $url = $this->createMobileUrl('index');
//                echo "<meta charset='utf-8'><script type='text/javascript'>
//                            alert('发布成功 ！');
//                         window.location.href='$url';
//                    </script>";
            }
        }
        load()->func('tpl');

        include $this->template('post');
    }
    public function doMobileDetail(){
        global $_W,$_GPC;
        $operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
        //	    $_W['siteroot'] = 'http://192.168.1.13/';
        $id = $_GPC['id'];
        if ($operation=='zan'){
            $data = array (
                'bbsid' => $_GPC ['id'],
                'weid' => $_W['uniacid'],
                'openid' => $_W['fans']['openid'],
                'createtime' => time()
            );
            $iszan = pdo_fetchcolumn("select count(*) from ".tablename('wwr_bbs_zan')." where openid = '".$_W['fans']['openid']."' and bbsid = ".$id);
            if($iszan){
                $count = pdo_fetchcolumn("select count(*) from ".tablename('wwr_bbs_zan')." where bbsid = ".$id);
                $tmp=array('status'=>'1','msg' => '重复点赞','count'=>$count);
            }else{
                $result = pdo_insert ('wwr_bbs_zan', $data );
                if($result){
                    $count = pdo_fetchcolumn("select count(*) from ".tablename('wwr_bbs_zan')." where bbsid = ".$id);
                    $tmp=array('status'=>'1','msg' => '已赞','count'=>$count);
                }else{
                    $tmp=array('status'=>'0','msg' => '点赞失败!');
                }
            }
            die(json_encode($tmp));
        }
        if ($operation=='fav'){
            $data = array (
                'bbsid' => $_GPC ['id'],
                'weid' => $_W['uniacid'],
                'openid' => $_W['fans']['openid'],
                'createtime' => time()
            );
            $isfav = pdo_fetchcolumn("select count(*) from ".tablename('wwr_bbs_fav')." where openid = '".$_W['fans']['openid']."' and bbsid = ".$id);
            if($isfav){
                $count = pdo_fetchcolumn("select count(*) from ".tablename('wwr_bbs_zan')." where bbsid = ".$id);
                $tmp=array('status'=>'1','msg' => '重复收藏');
            }else{
                $result = pdo_insert ('wwr_bbs_fav', $data );
                if($result){
                    $tmp=array('status'=>'1','msg' => '已收藏');
                }else{
                    $tmp=array('status'=>'0','msg' => '收藏失败!');
                }
            }
            die(json_encode($tmp));
        }
        if ($operation=='ajax'){
            $data = array (
                'pid' => $_GPC ['pid'],
                'weid' => $_W['uniacid'],
                'openid' => $_W['fans']['openid'],
                'title' => '',
                'content' => htmlspecialchars_decode($_GPC ['content']),
                'createtime' => time(),
                'status' => 1
            );
            $result = pdo_insert ('wwr_bbs', $data );
            if($result){
                $tmp=array('status'=>'1','msg' => '回复成功');
            }else{
                $tmp=array('status'=>'0','msg' => '回复失败');
            }
            die(json_encode($tmp));
        }
        $data = pdo_fetch ("SELECT * FROM " . tablename ('wwr_bbs') . " WHERE id = " . $id );
        $data['zan'] = pdo_fetchcolumn("select COUNT(*) from ".tablename('wwr_bbs_zan')." where bbsid = ".$id);
        $data['isfav'] = pdo_fetchcolumn("select count(*) from ".tablename('wwr_bbs_fav')." where openid = '".$_W['fans']['openid']."' and bbsid = ".$id);
        $data['iszan'] = pdo_fetchcolumn("select count(*) from ".tablename('wwr_bbs_zan')." where openid = '".$_W['fans']['openid']."' and bbsid = ".$id);
        pdo_query("update " . tablename('wwr_bbs') . " set hits = hits+1 where id=:id", array(":id" => $id));
        $hfdata = pdo_fetchall("select * from " .tablename('wwr_bbs'). " where pid = " .$id);
        foreach ($hfdata as &$v){
            $v['avatar'] = $this->getavatar($v['openid']);
            $v['nickname'] = $this->getnickname($v['openid']);
            $v['createtime'] = $this->from_time($v['createtime']);
        }
        //        if($data['pic']==''){$data['pic']=$this->nopic;}
        $pagetitle = $data['title'];
        if($data['pics']){
            $picsarr = explode(',',$data['pics']);
        }
        load()->func('tpl');

        include $this->template('detail');
    }


    public function doMobileMember(){
        global $_W,$_GPC;


        //        $_W['fans']['nickname'] = '小文文';
        //        $_W['fans']['avatar'] = 'http://wx.qlogo.cn/mmopen/0hGE2mScTT1tibHtM0HLyibibGDibWrQr7q6yX7Ltgib0GZIeGrBJWWPUb27B8iaCyJHWrpZjBMWLRsXY6nVGzUYiaC5PunDaYx5oVp/132';
        //        $_W['siteroot'] = 'http://localhost/';
        include $this->template('member');
    }

    public function doMobileMylist(){
        global $_W,$_GPC;
        $ajax = $_GPC['ajax'];
        $operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';

        if($ajax){
            $pindex = max(1, intval($_GPC['page']));
            //当前页码
            $psize = max(1, intval($_GPC['psize']));
            $condition = " pid = 0  and openid = '{$_W['fans']['openid']}' and weid = '{$_W['uniacid']}'";
            $field = "id, title, pic, createtime,openid";


            $activity = pdo_fetchall ("SELECT $field FROM " . tablename ('wwr_bbs') . " WHERE $condition ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);

            $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('wwr_bbs') . " WHERE $condition");

            foreach ($activity as &$v){
                $v['avatar'] = $this->getavatar($v['openid']);
                $v['nickname'] = $this->getnickname($v['openid']);
                $v['createtime'] = $this->from_time($v['createtime']);
                if($v['pic']==''){$v['pic']=$this->nopic;}
            }
            //array_merge数组拼接
            $tmp['lists']=$activity;
            $tmp['tpage']=(empty($psize) || $psize < 0) ? 1 : ceil($total / $psize);
            die(json_encode($tmp));
        }else{
            include $this->template('mylist');
        }
    }
    public function doMobileCanyu(){
        global $_W,$_GPC;
        $ajax = $_GPC['ajax'];
        $operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';

        if($ajax){
            $pindex = max(1, intval($_GPC['page']));
            //当前页码
            $psize = max(1, intval($_GPC['psize']));
            $condition = " pid <> 0  and openid = '{$_W['fans']['openid']}' and weid = '{$_W['uniacid']}'";
            $field = "id, pid,content, pic, createtime,openid";
            $activity = pdo_fetchall ("SELECT $field FROM " . tablename ('wwr_bbs') . " WHERE $condition ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
            $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('wwr_bbs') . " WHERE $condition");
            foreach ($activity as &$v){
                $v['avatar'] = $this->getavatar($v['openid']);
                $v['nickname'] = $this->getnickname($v['openid']);
                $v['createtime'] = $this->from_time($v['createtime']);
                if($v['pic']==''){$v['pic']=$this->nopic;}
            }
            //array_merge数组拼接
            $tmp['lists']=$activity;
            $tmp['tpage']=(empty($psize) || $psize < 0) ? 1 : ceil($total / $psize);
            die(json_encode($tmp));
        }else{
            include $this->template('canyu');
        }
    }
    public function doMobileFav(){
        global $_W,$_GPC;
        $ajax = $_GPC['ajax'];
        $operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';

        if($ajax){
            $pindex = max(1, intval($_GPC['page']));
            //当前页码
            $psize = max(1, intval($_GPC['psize']));
            $condition = " openid = '".$_W['fans']['openid']."' and weid = '{$_W['uniacid']}'";
            $field = "*";
            $activity = pdo_fetchall ("SELECT $field FROM " . tablename ('wwr_bbs_fav') . " WHERE $condition ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
            $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('wwr_bbs_fav') . " WHERE $condition");
            foreach ($activity as &$v){
                $v['title'] = $this->getbbstitle($v['bbsid']);
            }
            //array_merge数组拼接
            $tmp['lists']=$activity;
            $tmp['tpage']=(empty($psize) || $psize < 0) ? 1 : ceil($total / $psize);
            die(json_encode($tmp));
        }else{
            include $this->template('fav');
        }
    }
    public function doWebBbs() {
        global $_W,$_GPC;
        $ops = array('manage','check');
        $op = in_array($_GPC['op'],$ops)?$_GPC['op']:'manage';
        $index=isset($_GPC['page'])?$_GPC['page']:1;
        $pageIndex = $index;
        $pageSize = 10;
        $contion = 'limit '.($pageIndex-1) * $pageSize .','. $pageSize;
        //        if($op['manage']){
        $total= pdo_fetchcolumn('select count(*) from ' . tablename('wwr_bbs') ." WHERE `weid` = :uniacid " ,array(':uniacid'=>$_W['uniacid']));
        $page = pagination($total,$pageIndex,$pageSize);
        $datalist = pdo_fetchall("select * from ".tablename('wwr_bbs')." where `weid`=:uniacid order by `id` desc ".$contion,array(':uniacid'=>$_W['uniacid']));

        //        }
        //这个操作被定义用来呈现 管理中心导航菜单
        include $this->template('bbs');
        //这个操作被定义用来呈现 管理中心导航菜单
    }
    public function doWebDeleteajax(){
        global $_GPC,$_W;
        $data = array (
            'id' => $_GPC ['id'],
            'weid' => $_W['uniacid']
        );
        $result = pdo_delete('wwr_bbs',$data);
        if($result){
            $tmp=array('status'=>'1','msg' => '删除成功');
        }else{
            $tmp=array('status'=>'0','msg' => '删除失败');
        }
        die(json_encode($tmp));
    }
    public function doWebbbs_category()
    {
        global $_GPC, $_W;
        $operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
        if ($operation == 'display') {
            if (!empty($_GPC['displayorder'])) {
                foreach ($_GPC['displayorder'] as $id => $displayorder) {
                    pdo_update('wwr_bbs_category', array('displayorder' => $displayorder), array('id' => $id));
                }
                message('分类排序更新成功！', $this->createWebUrl('bbs_category', array('op' => 'display')), 'success');
            }
            $children = array();
            $category = pdo_fetchall("SELECT * FROM " . tablename('wwr_bbs_category') . " WHERE weid = '{$_W['uniacid']}' ORDER BY parentid ASC, displayorder DESC");
            foreach ($category as $index => $row) {
                if (!empty($row['parentid'])) {
                    $children[$row['parentid']][] = $row;
                    unset($category[$index]);
                }
            }
            include $this->template('bbs_category');
        } elseif ($operation == 'post') {
            $parentid = intval($_GPC['parentid']);
            $id = intval($_GPC['id']);
            if (!empty($id)) {
                $item = pdo_fetch("SELECT * FROM " . tablename('wwr_bbs_category') . " WHERE id = '$id'");
            } else {
                $item = array(
                    'displayorder' => 0,
                );
            }

            if (!empty($parentid)) {
                $parent = pdo_fetch("SELECT id, cname FROM " . tablename('wwr_bbs_category') . " WHERE id = '$parentid'");
                if (empty($parent)) {
                    message('抱歉，上级分类不存在或是已经被删除！', $this->createWebUrl('post'), 'error');
                }
            }
            if (checksubmit('submit')) {
                if (empty($_GPC['cname'])) {
                    message('抱歉，请输入分类名称！');
                }

                $data = array(
                    'weid' => $_W['uniacid'],
                    'cname' => $_GPC['cname'],
                    'displayorder' => intval($_GPC['displayorder']),
                    'parentid' => intval($parentid),
                    'description' => $_GPC['description'],
                    'status' => intval($_GPC['status'])
                );
                if (!empty($id)) {
                    unset($data['parentid']);
                    pdo_update('wwr_bbs_category', $data, array('id' => $id));
                } else {
                    pdo_insert('wwr_bbs_category', $data);
                    $id = pdo_insertid();
                }
                message('更新分类成功！', $this->createWebUrl('bbs_category', array('op' => 'display')), 'success');
            }
            include $this->template('bbs_category');
        } elseif ($operation == 'delete') {
            $id = intval($_GPC['id']);
            $category = pdo_fetch("SELECT id, parentid FROM " . tablename('wwr_bbs_category') . " WHERE id = '$id'");
            if (empty($category)) {
                message('抱歉，分类不存在或是已经被删除！', $this->createWebUrl('bbs_category', array('op' => 'display')), 'error');
            }
            pdo_delete('wwr_bbs_category', array('id' => $id, 'parentid' => $id), 'OR');
            message('分类删除成功！', $this->createWebUrl('bbs_category', array('op' => 'display')), 'success');
        } else if ($operation == 'query') {
            $kwd = trim($_GPC['keyword']);
            $sql = 'SELECT id, cname as title FROM ' . tablename('wwr_bbs_category') . ' WHERE `weid`=:weid';
            $ordersql = ' ORDER BY parentid ASC, displayorder DESC';
            $params = array();
            $params[':weid'] = $_W['uniacid'];
            if (!empty($kwd)) {
                $sql .= " AND `cname` LIKE :cname";
                $params[':cname'] = "%{$kwd}%";
            }
            $sql = $sql . $ordersql;
            $ds = pdo_fetchall($sql, $params);
            include $this->template('bbs_category_query');

        }
    }
    public function doWebConfig() {
        include $this->template('config');
        //这个操作被定义用来呈现 管理中心导航菜单
    }

    //读取用户昵称
    public function getnickname($openid){
        $tmp = mc_fansinfo($openid);
        return $tmp['nickname'];
    }
    //读取用户头像
    public function getavatar($openid){
        $tmp = mc_fansinfo($openid);
        return $tmp['avatar'];
    }
    //获取帖子标题
    public function getbbstitle($id){
        $title = pdo_fetchcolumn("select title from ".tablename('wwr_bbs')." where id = $id");
        return $title;
    }
    /*
     * 精确时间间隔函数
     * $time 发布时间 如 1356973323
     * $str 输出格式 如 Y-m-d H:i:s
     * 半年的秒数为15552000，1年为31104000，此处用半年的时间
     */
    public function from_time($time,$str=''){
        isset($str)?$str:$str='m-d';
        $way = time() - $time;
        $r = '';
        if($way < 60){
            $r = '刚刚';
        }elseif($way >= 60 && $way <3600){
            $r = floor($way/60).'分钟前';
        }elseif($way >=3600 && $way <86400){
            $r = floor($way/3600).'小时前';
        }elseif($way >=86400 && $way <2592000){
            $r = floor($way/86400).'天前';
        }elseif($way >=2592000 && $way <15552000){
            $r = floor($way/2592000).'个月前';
        }else{
            $r = date("$str",$time);
        }
        return $r;
    }
}